package cn.edu.zafu.bigdata.XuShuXin.Exp1203;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author: aluvfy
 * @description:
 * @date: 2024/12/3 10:28
 */
public class UDPServer_time_xsx {
    public static void main(String[] args) throws Exception {
        int port = 12345; // 服务端监听的端口号
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[1024];
        byte[] sendData;

        while (true) {
            //接受客户端的数据包，并转换为字符串
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);
            String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Received: " + sentence);

            if ("Time".equals(sentence.trim())) {
                //发送数据包给客户端
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                sendData = time.getBytes();
                InetAddress IPAddress = receivePacket.getAddress();
                int portClient = receivePacket.getPort();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, portClient);
                serverSocket.send(sendPacket);
            }
        }
    }
}
